<template>
  <div>
    <el-card class="card">
      <!-- 老人信息 -->
      <div class="header">
        <span class="line" />
        老人信息
      </div>
      <!-- 表单 -->
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="老人姓名：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入老人姓名" clearable />
        </el-form-item>
        <el-form-item label="老人性别：" prop="gender">
          <el-select v-model="ruleForm.gender" placeholder="请选择" clearable>
            <el-option label="男" :value="1" />
            <el-option label="女" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号：" prop="idCard">
          <el-input v-model="ruleForm.idCard" placeholder="请输入老人身份证号" clearable />
        </el-form-item>
        <el-form-item label="老人状况：" prop="status">
          <el-input
            v-model="ruleForm.status"
            type="textarea"
            placeholder="请输入老人状况"
            clearable
          />
        </el-form-item>
      </el-form>
      <!-- 家属信息 -->
      <div class="family">
        <div class="header">
          <span class="line" />
          家属信息
        </div>
        <el-button type="primary" @click="addFamily">新增家属</el-button>
      </div>
      <!-- 家属信息表格 -->
      <el-table :data="ruleForm.family" style="width: 100%">
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="name" label="姓名" width="180" />
        <el-table-column prop="gender" label="性别">
          <template #default="scope">{{ scope.row.gender == 1 ? "男" : "女" }}</template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" />
        <el-table-column prop="mobile" label="联系电话" />
        <el-table-column prop="address" label="联系地址" />
        <el-table-column prop="relation" label="与老人关系" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" text @click="updateFamily(scope.row)">编辑</el-button>
            <el-button type="primary" text @click="delFamily(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 需求总结 -->
      <div class="header">
        <span class="line" />
        家属信息
      </div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="房间需求：" prop="roomRequire">
          <el-input
            v-model="ruleForm.roomRequire"
            type="textarea"
            placeholder="请输入房间需求"
            clearable
          />
        </el-form-item>
        <el-form-item label="意向描述：" prop="content">
          <el-input
            v-model="ruleForm.content"
            type="textarea"
            placeholder="请输入意向描述"
            clearable
          />
        </el-form-item>
        <el-form-item class="btns">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save(ruleFormRef)">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增家属dialog -->
    <AddFamily v-if="dialogVisible" :family="familyData" @close="closeHandle" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRoute } from "vue-router";
import { AddParams, FamilyData } from "../../api/market/customer/type";
import { FormInstance, FormRules } from "element-plus";
import AddFamily from "../../components/market/customer/AddFamily.vue";
import { addCustomer, getCustomerModel, updateCustomer } from "@/api/market/customer/customer";
import router from "@/router";

const route = useRoute();

let currentId = ref(0);

onMounted(() => {
  // console.log("111ruleFormId");

  // console.log("routeid", route.params.id);
  if (route.params.id) {
    currentId.value = Number(route.params.id);
    getModel();
  }
});

//获取单条客户信息
const getModel = async () => {
  let res = await getCustomerModel(currentId.value);
  // console.log("7777res",res);

  if (res) {
    Object.assign(ruleForm, res);
  }
};

const ruleFormRef = ref<FormInstance>();

export interface tableDataParams {
  id: number;
  name: string;
  mobile: string;
  idCard: string;
  relation: string;
  gender: number;
  address: string;
}

//表格数据
const tableData: tableDataParams[] = [
  {
    id: 0,
    name: "",
    mobile: "",
    idCard: "",
    relation: "",
    gender: 0,
    address: "",
  },
];

//添加老人信息
const ruleForm = reactive<AddParams>({
  name: "",
  mobile: "",
  gender: undefined,
  birthday: "",
  status: "",
  idCard: "",
  roomRequire: "",
  content: "",
  state: 1,
  source: "在线咨询",
  family: [],
});

//新增家属dialog
let dialogVisible = ref(false);

//规则
const rules = reactive<FormRules<AddParams>>({
  name: [{ required: true, message: "请输入老人姓名", trigger: "blur" }],
  gender: [
    {
      required: true,
      message: "请选择性别",
      trigger: "change",
    },
  ],
  idCard: [{ required: true, message: "请输入老人身份证号", trigger: "blur" }],
  status: [{ required: true, message: "请输入老人状况", trigger: "blur" }],
  roomRequire: [{ required: true, message: "请输入房间需求", trigger: "blur" }],
  content: [{ required: true, message: "请输入意向描述", trigger: "blur" }],
});

//关闭弹出层
const closeHandle = (data: any) => {
  dialogVisible.value = false;
  console.log("989787", data);
  if (data) {
    if (data.customerId) {
      //修改
      ruleForm.family.forEach((item, index) => {
        ruleForm.family.splice(index, 1, data);
      });
    } else {
      //添加
      ruleForm.family.push(data);
      ruleForm.family.forEach((item: FamilyData, index) => {
        item.id = index + 1;
      });
    }
  }
};

//新增家属信息
const addFamily = () => {
  //清空
  familyData = {
    id: 0,
    name: "",
    mobile: "",
    idCard: "",
    relation: "",
    gender: 0,
    address: "",
  };
  dialogVisible.value = true;
};

//删除家属信息
const delFamily = (id: number) => {
  ElMessageBox.confirm("是否确认删除该家属", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ruleForm.family.splice(id - 1, 1);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消 canceled",
      });
    });

  // console.log("id", id);
};

let familyData: FamilyData = reactive({
  id: 0,
  name: "",
  mobile: "",
  idCard: "",
  relation: "",
  gender: 0,
  address: "",
});

//修改家属信息
const updateFamily = (item: FamilyData) => {
  dialogVisible.value = true;
  if (item) {
    familyData = item;
  }
  console.log("111", item);
};

const emit = defineEmits(["sendValue"]);

//添加潜在用户
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (currentId.value) {
        //修改
        let updateRes = await updateCustomer(ruleForm);
        console.log("updateRes", updateRes);
      } else {
        //添加
        let res = await addCustomer(ruleForm);
      }

      // if (res) {
      router.push("/market/customer");
      // }
      // console.log("777", res);
    } else {
      ElMessage({
        message: "error submit!",
        type: "warning",
      });
    }
  });
};

//取消
const cancel = () => {
  router.push("/market/customer");
};
</script>

<style scoped lang="less">
.card {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;

  .header {
    height: 50px;
    display: flex;
    align-items: center;
    font-weight: 700;

    .line {
      display: block;
      width: 6px;
      height: 20px;
      background-color: #529bfd;
      margin-right: 8px;
    }
  }

  .demo-ruleForm {
    margin-top: 20px;

    .el-input {
      width: 400px;
    }

    .el-select {
      width: 400px;
    }

    .el-textarea {
      width: 400px;
    }

    .btns {
      width: 200px;
      margin: 0 auto;
    }
  }
}
</style>
